package com.bawei.module_main.ui

import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_mvi.Router
import com.bawei.lib_common.utils.StartupOptimizer
import com.bawei.lib_mvi.base.BaseActivity
import com.bawei.lib_storage.mmkv.AuthMMKV
import com.bawei.module_main.R
import com.bawei.module_main.databinding.ActivitySplashBinding
import com.umeng.analytics.MobclickAgent
import kotlinx.coroutines.*


class SplashActivity : BaseActivity() {

    private val binding: ActivitySplashBinding by lazy {
        ActivitySplashBinding.inflate(layoutInflater)
    }

    private val mainScope = CoroutineScope(Dispatchers.Main + SupervisorJob())

    companion object {
        // 最小显示时间 - 进一步减少到1秒
        private const val SPLASH_MIN_DELAY: Long = 1_000
        
        // 静态标志位，防止重复跳转
        private var hasNavigatedGlobally = false
    }

    override fun getLayoutRootView(): View {
        return binding.root
    }

    // 初始化完成后操作
    private var actionAfterInitFinished: (() -> Unit)? = null
    private var isInitFinished = false
    private var isMinTimeReached = false
    private var hasNavigatedToTarget = false

    override fun initView() {
        StartupOptimizer.recordStage("SplashActivity开始初始化UI")

        // 重置静态标志位，确保每次启动都能正常跳转
        hasNavigatedGlobally = false
        
        // 直接设置图片，不做复杂处理
        binding.splashPic.setImageResource(R.mipmap.bg_splash)
        StartupOptimizer.recordStage("SplashActivity UI初始化完成")
    }

    override fun initData() {
        StartupOptimizer.recordStage("SplashActivity开始初始化数据")

        // 设置跳过按钮
        binding.countDownSkip.onSkipListener = {
            checkSkip()
        }

        // 开始倒计时
        binding.countDownSkip.startCountDown()

        // 启动异步初始化
        startAsyncInit()

        // 设置最小显示时间 - 进一步减少等待时间
        Handler(Looper.getMainLooper()).postDelayed({
            isMinTimeReached = true
            Log.d("SplashActivity", "最小显示时间到达")
            checkSkip()
        }, SPLASH_MIN_DELAY)
    }

    private fun startAsyncInit() {
        mainScope.launch(Dispatchers.IO) {
            try {
                StartupOptimizer.recordStage("开始异步初始化")
                // 最小化预加载，只做必要的初始化
                preloadData()
                withContext(Dispatchers.Main) {
                    isInitFinished = true
                    StartupOptimizer.recordStage("异步初始化完成")
                    Log.d("SplashActivity", "异步初始化完成")
                    checkSkip()
                }
            } catch (e: Exception) {
                // 初始化失败，也要跳转
                withContext(Dispatchers.Main) {
                    isInitFinished = true
                    StartupOptimizer.recordStage("异步初始化失败")
                    Log.d("SplashActivity", "异步初始化失败")
                    checkSkip()
                }
            }
        }
    }

    private suspend fun preloadData() {
        // 最小化预加载，几乎不耗时
        withContext(Dispatchers.IO) {

        }
    }

    private fun checkSkip() {
        Log.d("SplashActivity", "checkSkip() 被调用: isInitFinished=$isInitFinished, isMinTimeReached=$isMinTimeReached, hasNavigatedToTarget=$hasNavigatedToTarget")
        
        // 只有当初始化完成且最小时间到达时才跳转
        if (isInitFinished && isMinTimeReached && !hasNavigatedToTarget) {
            Log.d("SplashActivity", "满足跳转条件，开始检查登录状态")
            if (AuthMMKV.hasLogin()) {
                toMain()
            } else {
                toLogin()
            }
        } else {
            Log.d("SplashActivity", "不满足跳转条件: isInitFinished=$isInitFinished, isMinTimeReached=$isMinTimeReached, hasNavigatedToTarget=$hasNavigatedToTarget")
        }
    }

    private fun toMain() {
        if (!isFinishing && !hasNavigatedToTarget && !hasNavigatedGlobally) {
            hasNavigatedToTarget = true
            hasNavigatedGlobally = true
            Log.d("SplashActivity", "跳转到MainActivity")
            ARouter.getInstance().build(Router.Ui.MainActivity).navigation()
            actionAfterInitFinished?.invoke()
            finish()
        } else {
            Log.d(
                "SplashActivity",
                "toMain() 被阻止: isFinishing=$isFinishing, hasNavigatedToTarget=$hasNavigatedToTarget, hasNavigatedGlobally=$hasNavigatedGlobally"
            )
        }
    }

    private fun toLogin() {
        if (!isFinishing && !hasNavigatedToTarget && !hasNavigatedGlobally) {
            hasNavigatedToTarget = true
            hasNavigatedGlobally = true
            Log.d("SplashActivity", "跳转到LoginActivity")
            ARouter.getInstance().build(Router.Ui.USER_ACTIVITY).navigation()
            actionAfterInitFinished?.invoke()
            finish()
        } else {
            Log.d(
                "SplashActivity",
                "toLogin() 被阻止: isFinishing=$isFinishing, hasNavigatedToTarget=$hasNavigatedToTarget, hasNavigatedGlobally=$hasNavigatedGlobally"
            )
        }
    }

    override fun onResume() {
        super.onResume()
        MobclickAgent.onPageStart("Splash")
    }

    override fun onPause() {
        super.onPause()
        MobclickAgent.onPageEnd("Splash")
    }

    override fun onDestroy() {
        super.onDestroy()
        mainScope.cancel()

        // 完成启动记录
        StartupOptimizer.finishRecord(true)

        // 输出优化建议
        val suggestions = StartupOptimizer.getOptimizationSuggestions()
        if (suggestions.isNotEmpty()) {
            suggestions.forEach { suggestion ->
                android.util.Log.w("StartupOptimizer", suggestion)
            }
        }
    }
}
